#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()


from celery import shared_task
import json, datetime, requests, time

from vouchers.models import AliDiscountCouponInfo, AliDiscountCoupon
from customers.utils import AlipayOpen as c_AlipayOpen, favor_distributed_coupons, favor_query_coupons, favor_distributed_coupons_sichun, favor_query_coupons_sichun
from equity_mall.utils.utils import encrypt_pkcs7_padding
from equity_mall.utils.utils import random_str
from users.models import CustomerUserVice
from equity_mall.utils.wash_level1 import haizhui_get_sign
from activities.models import Channel


@shared_task
def dispose_voucher_result(data):
    instance = AliDiscountCouponInfo.objects.get(id=data['id'])
    user = instance.companyuser
    if instance.status != 0:
        return '订单状态有误,拦截派发'
    activity = instance.alidiscountcoupon
    activity_id = activity.id
    request_data = {}
    if activity.coupon_channel == 1:
        alipay_obj = c_AlipayOpen()
        template_id = activity.template_id
        login_id = instance.login_id
        out_biz_no = instance.out_biz_no
        result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
        if result['code'] != '10000':
            instance.status = 14
            instance.return_msg = result['sub_msg']
            instance.gmt_create = datetime.datetime.now()
            instance.save()
            while True:
                activity = AliDiscountCoupon.objects.get(id=activity_id)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count - 1
                activity_new_remain_number = activity_origin_remain_number + 1
                result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result1 == 0:
                    continue
                break
            request_data['code'] = 400
            request_data['message'] = '发券失败'
            if user.id in [1, 40535, 65375]:
                text_data = {}
                text_data['err_code_des'] = result['sub_msg']
                text_data['out_biz_no'] = instance.out_biz_order
                text_data['create_time'] = instance.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                text_data['status_display'] = '领取失败'
                ciphertext = encrypt_pkcs7_padding(json.dumps(text_data), user.authen_key)
                request_data['ciphertext'] = ciphertext
            else:
                request_data['err_code_des'] = result['sub_msg']
                request_data['out_biz_no'] = instance.out_biz_order
                request_data['create_time'] = instance.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                request_data['status_display'] = '领取失败'
        else:
            voucher_id = result['voucher_id']
            result = json.loads(alipay_obj.voucherquery(voucher_id))
            instance.voucher_id = voucher_id
            instance.template_id = result['template_id']
            instance.gmt_active = result['gmt_active']
            instance.gmt_expired = result['gmt_expired']
            instance.total_amount = result['total_amount']
            instance.gmt_create = result['gmt_create']
            instance.available_amount = result['available_amount']
            instance.name = result['name']
            instance.status = 1
            instance.save()
            request_data['code'] = 200
            request_data['message'] = '发券成功'
            if user.id in [1, 40535, 65375]:
                text_data = {}
                text_data['err_code_des'] = ''
                text_data['out_biz_no'] = instance.out_biz_order
                text_data['create_time'] = instance.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                text_data['expired_time'] = result['gmt_expired']
                text_data['status_display'] = '待核销'
                try:
                    text_data['active_time'] = result['gmt_active']
                except:
                    pass
                text_data['total_amount'] = str(instance.total_amount)
                ciphertext = encrypt_pkcs7_padding(json.dumps(text_data), user.authen_key)
                request_data['ciphertext'] = ciphertext
            else:
                request_data['err_code_des'] = ''
                request_data['out_biz_no'] = instance.out_biz_order
                request_data['create_time'] = instance.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                request_data['expired_time'] = result['gmt_expired']
                request_data['status_display'] = '待核销'
                request_data['total_amount'] = instance.total_amount
                request_data['voucher_id'] = voucher_id
                try:
                    request_data['active_time'] = result['gmt_active']
                except:
                    pass
    elif activity.coupon_channel == 2:
        out_biz_no = instance.out_biz_no
        appid = instance.appid
        openid = instance.user_id
        if activity.platform_id == 13:
            distribute_channel = Channel.objects.get(id=13)
        else:
            distribute_channel = Channel.objects.get(id=9)
        data_json = {
            "stock_id": activity.template_id,
            "out_request_no": out_biz_no,
            "appid": appid,
            "stock_creator_mchid": activity.platform.mchid
        }
        data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
        if 'code' in data_dict:
            instance.status = 14
            instance.return_msg = data_dict['message']
            instance.gmt_create = datetime.datetime.now()
            instance.save()
            while True:
                activity = AliDiscountCoupon.objects.get(id=activity_id)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count - 1
                activity_new_remain_number = activity_origin_remain_number + 1
                result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result1 == 0:
                    continue
                break
            request_data['code'] = 400
            request_data['message'] = '发券失败'
            if user.id in [1, 40535, 65375]:
                text_data = {}
                text_data['err_code_des'] = data_dict['message']
                text_data['out_biz_no'] = instance.out_biz_order
                text_data['create_time'] = instance.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                text_data['status_display'] = '领取失败'
                ciphertext = encrypt_pkcs7_padding(json.dumps(text_data), user.authen_key)
                request_data['ciphertext'] = ciphertext
            else:
                request_data['err_code_des'] = data_dict['message']
                request_data['out_biz_no'] = instance.out_biz_order
                request_data['create_time'] = instance.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                request_data['status_display'] = '领取失败'
        else:
            coupon_id = data_dict['coupon_id']
            result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
            instance.voucher_id = coupon_id
            instance.template_id = result['stock_id']
            instance.gmt_active = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
            instance.gmt_expired = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
            instance.total_amount = result['normal_coupon_information']['coupon_amount'] / 100
            instance.gmt_create = datetime.datetime.now()
            instance.available_amount = result['normal_coupon_information']['coupon_amount'] / 100
            instance.name =result['coupon_name']
            instance.status = 1
            instance.save()
            request_data['code'] = 200
            request_data['message'] = '发券成功'
            if user.id in [1, 40535, 65375]:
                text_data = {}
                text_data['err_code_des'] = ''
                text_data['out_biz_no'] = instance.out_biz_order
                text_data['create_time'] = instance.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                text_data['expired_time'] = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
                text_data['status_display'] = '待核销'
                text_data['total_amount'] = str(instance.total_amount)
                try:
                    text_data['active_time'] = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
                except:
                    pass
                ciphertext = encrypt_pkcs7_padding(json.dumps(text_data), user.authen_key)
                request_data['ciphertext'] = ciphertext
            else:
                request_data['err_code_des'] = ''
                request_data['out_biz_no'] = instance.out_biz_order
                request_data['create_time'] = instance.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                request_data['expired_time'] = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
                request_data['status_display'] = '待核销'
                request_data['total_amount'] = instance.total_amount
                request_data['voucher_id'] = coupon_id
                try:
                    request_data['active_time'] = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
                except:
                    pass
    elif activity.coupon_channel == 3:
        voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
        gmt_create = datetime.datetime.now()
        alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
        if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
            gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
            gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
        elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
            gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
            gmt_active = gmt_create
        else:
            gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
            gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
        instance.voucher_id = voucher_id
        instance.template_id = activity.template_id
        instance.gmt_active = gmt_active
        instance.gmt_expired = gmt_expired
        instance.total_amount = activity.amount
        instance.gmt_create = gmt_create
        instance.available_amount = activity.amount
        instance.name = activity.activity_name
        instance.status = 1
        customeruservice = CustomerUserVice.objects.filter(ylx_openid=instance.user_id).first()
        if customeruservice:
            instance.customeruservice_id = customeruservice.id
        instance.save()
        request_data['code'] = 200
        request_data['message'] = '发券成功'
        if user.id in [1, 40535, 65375]:
            text_data = {}
            text_data['err_code_des'] = ''
            text_data['out_biz_no'] = instance.out_biz_order
            text_data['create_time'] = instance.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
            text_data['expired_time'] = gmt_expired.strftime('%Y-%m-%d %H:%M:%S')
            text_data['status_display'] = '待核销'
            text_data['total_amount'] = str(instance.total_amount)
            ciphertext = encrypt_pkcs7_padding(json.dumps(text_data), user.authen_key)
            request_data['ciphertext'] = ciphertext
        else:
            request_data['err_code_des'] = ''
            request_data['out_biz_no'] = instance.out_biz_order
            request_data['create_time'] = instance.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
            request_data['expired_time'] = gmt_expired.strftime('%Y-%m-%d %H:%M:%S')
            request_data['status_display'] = '待核销'
            request_data['total_amount'] = str(instance.total_amount)
            request_data['voucher_id'] = voucher_id
        if user.id in [1, 404]:
            linkUrl = f'pages/ylx_transition/ylx_transition?path=pages/coupon_pro_list/coupon_pro_list&coupon_id={voucher_id}'
            linkAppId = 'wx950122ad80dc97c9'
            contentLink = {
                "linkAppId": linkAppId,
                "linkUrl": linkUrl
            }
            request_data['contentLink'] = contentLink
    try:
        print(request_data)
        if instance.notify_url:
            # if user.id in [1, 40535]:
            #     headers = {'Content-Type': 'application/x-www-form-urlencoded'}
            #     response = requests.post(url=instance.notify_url, data=request_data, headers=headers)
            # else:
            headers = {'Content-Type': 'application/json'}
            response = requests.request('post', url=instance.notify_url, data=json.dumps(request_data), headers=headers)
            print(response.status_code)
            print(response.content)
    except Exception as e:
        print(e)
        pass
    return '写入成功'


@shared_task
def haizhui_dispose_voucher_result(data):
    instance = AliDiscountCouponInfo.objects.get(id=data['id'])
    user = instance.companyuser
    if instance.status != 0:
        return '订单状态有误,拦截派发'
    activity = instance.alidiscountcoupon
    activity_id = activity.id
    request_data = {}
    out_biz_no = instance.out_biz_no
    appid = instance.appid
    openid = instance.user_id
    if activity.platform_id == 13:
        distribute_channel = Channel.objects.get(id=13)
    else:
        distribute_channel = Channel.objects.get(id=9)
    data_json = {
        "stock_id": activity.template_id,
        "out_request_no": out_biz_no,
        "appid": appid,
        "stock_creator_mchid": activity.platform.mchid
    }
    data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
    Appkey = 'SN8958632086'
    AppSeret = 'DBXRZYRVZUI2CTGQOXPOOEVYUCG7Z4XT'
    # Appkey = 'SN3197527788'
    # AppSeret = 'OTB5MG1OVECHDKWH0SBJMXICQSR6CKKM'
    timestamp = int(time.time()*1000)
    if 'code' in data_dict:
        instance.status = 14
        instance.return_msg = data_dict['message']
        instance.gmt_create = datetime.datetime.now()
        instance.save()
        while True:
            activity = AliDiscountCoupon.objects.get(id=activity_id)
            activity_origin_send_count = activity.send_count
            activity_origin_remain_number = activity.remain_number
            activity_new_send_count = activity_origin_send_count - 1
            activity_new_remain_number = activity_origin_remain_number + 1
            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                send_count=activity_new_send_count,
                remain_number=activity_new_remain_number
            )
            if result1 == 0:
                continue
            break
        status = 'RECHARGE_FAIL'
    else:
        coupon_id = data_dict['coupon_id']
        result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
        instance.voucher_id = coupon_id
        instance.template_id = result['stock_id']
        instance.gmt_active = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
        instance.gmt_expired = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
        instance.total_amount = result['normal_coupon_information']['coupon_amount'] / 100
        instance.gmt_create = datetime.datetime.now()
        instance.available_amount = result['normal_coupon_information']['coupon_amount'] / 100
        instance.name =result['coupon_name']
        instance.status = 1
        instance.save()
        status = 'SUCCESS'
    try:
        # print(request_data)
        headers = {"User-Agent": "PostmanRuntime/7.28.2"}
        if instance.notify_url:
            sign_data = {}
            sign_data['order_no'] = instance.out_biz_order
            sign_data['supplier_no'] = Appkey
            sign_data['status'] = status
            sign_data['timestamp'] = str(timestamp)
            sign = haizhui_get_sign(sign_data, AppSeret)
            url = f'{instance.notify_url}?order_no={instance.out_biz_order}&supplier_no={Appkey}&status={status}&sign={sign}&timestamp={timestamp}'
            print(url)
            # response = requests.request('get', url=url)
            response = requests.get(url=url, headers=headers)
            content = response.text
            if content != "OK":
                time.sleep(5)
                response = requests.get(url=url, headers=headers)
                content = response.text
                if content != "OK":
                    time.sleep(5)
                    response = requests.get(url=url, headers=headers)
            print(response.status_code)
            print(response.content)
    except Exception as e:
        print(e)
        pass
    return '写入成功'

